package com.mingqijia.gassafety.console.controller;

import cn.hutool.http.HttpRequest;
import com.gap.basic.base.CommonResponse;
import com.gap.cache.redis.RedisCache;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.webserver.request.ForwardRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 实时状态
 *
 * @author guoliang.lao
 * @since 2022-02-18
 */

@Slf4j
@Api(tags = "转发本安接口")
@RestController(value = "ForwardController")
@RequestMapping("/business/v1/forward")
public class ForwardController {

    @Autowired
    RedisCache cacheManager;

    @ApiOperation("get方式转发")
    @RequestMapping(value = "get", method = RequestMethod.GET)
    public CommonResponse<Object> get(@RequestParam @ApiParam(value = "params") String params,
                                       @RequestParam @ApiParam(value = "url") String url){
        String username = ApplicationUtils.getWorkingUser().getUsername();
        String cacheKey = String.format(Constants.CACHE_KEY_BEN_TOKEN, username);
        String oldToken = cacheManager.getCacheObject(cacheKey);

        url = url + "?"+params;
        log.info("url:"+url);
        HttpRequest request = HttpRequest.get(url);
        request.header("Authorization","Bearer "+oldToken);
        String body = request.execute().body();
        log.info(body);
        return CommonResponse.success(body);
    }


    @ApiOperation("post方式转发")
    @RequestMapping(value = "post", method = RequestMethod.POST)
    public CommonResponse<Object> post(@RequestBody ForwardRequest req){
        String username = ApplicationUtils.getWorkingUser().getUsername();
        String cacheKey = String.format(Constants.CACHE_KEY_BEN_TOKEN, username);
        String oldToken = cacheManager.getCacheObject(cacheKey);

        log.info("url:"+req.getUrl());
        HttpRequest request = HttpRequest.post(req.getUrl());
        request.header("Authorization","Bearer "+oldToken);
        request.body(req.getParams().toString());
        log.info(req.getParams().toString());
        String body = request.execute().body();
        log.info(body);
        return CommonResponse.success(body);
    }
}

